import { videoFrameCanvasId } from '../constant/video';

export const getVideoFrame = () => {
  return new Promise<string[]>((resolve, reject) => {
    const video = document.createElement('video');
    video.src = 'http://localhost:3000/demon.mp4';
    const frames: Array<string> = [];
    let videoDuration = 0;
    let canvas = document.getElementById(videoFrameCanvasId) as HTMLCanvasElement | null;

    if (canvas) {
      document.body.removeChild(canvas);
      canvas = null;
    }

    let currentTime = 0;

    video.oncanplay = () => {
      const { videoWidth, videoHeight, duration } = video;
      if (!canvas) {
        canvas = document.createElement('canvas');
        canvas.id = videoFrameCanvasId;
        canvas.style.position = 'absolute';
        canvas.style.zIndex = '-999';
        canvas.style.top = '0';
        canvas.width = videoWidth;
        canvas.height = videoHeight;
        videoDuration = duration;
        video.currentTime = currentTime;
        document.body.appendChild(canvas);
      }
    };

    video.ontimeupdate = () => {
      if (canvas && currentTime <= videoDuration) {
        const ctx = canvas.getContext('2d');
        ctx?.drawImage(video, 0, 0);
        frames.push(canvas.toDataURL());
        currentTime += 0.1;
        video.currentTime = currentTime;
        return;
      }
      resolve(frames);
    };
  });
};
